package com.shengwei.truck.driver.view.ui.mine.userinfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.lifecycle.Observer;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.TimeCount;
import com.shengwei.truck.driver.databinding.ActivityRegistBinding;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.app.WebViewBrowser;
import com.shengwei.truck.driver.view.ui.settings.SettingsActivity;
import com.shengwei.truck.driver.vm.RegistViewModel;
import java.lang.ref.WeakReference;

/**
 * 注册页面
 */
public class RegistActivity extends BaseActivity<RegistViewModel, ActivityRegistBinding> implements View.OnClickListener {
    private String mMobileNum;
    private String mPwd;
    private String mPwdSure;
    private String mSmsCode;
    private TimeCount mSmsTimeCount;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initLiveDataObersve();
        mSmsTimeCount = new TimeCount(mDataBinding.btGetSmsCode,60*1000,1000);
        this.getLifecycle().addObserver(mSmsTimeCount);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_regist;
    }

    /**
     * 初始化UI控件
     */
    private void initView() {
        mDataBinding.btGetSmsCode.setOnClickListener(this);
        mDataBinding.btSureRegist.setOnClickListener(this);
        mDataBinding.tvPrivacy.setOnClickListener(this);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle(R.string.registy);
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听获取验证码成功
        mViewModel.getSmsLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        if (mSmsTimeCount != null){
                            mSmsTimeCount.start();
                        }
                        Toast.makeText(RegistActivity.this, R.string.smscode_ok,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        //监听注册成功
        mViewModel.getRegistLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        Toast.makeText(RegistActivity.this, R.string.regist_ok,Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(RegistActivity.this,LoginActivity.class);
                        i.putExtra("username",mMobileNum);
                        startActivity(i);
                    }
                });
            }
        });
    }

    /**
     * 跳转到浏览器网页显示使用说明等文章
     * @param url
     * @param pageTitle
     */
    public void gotoWebviewBrowser(String url,String pageTitle) {
        Intent goReadMe = new Intent(RegistActivity.this, WebViewBrowser.class);
        goReadMe.putExtra("url",url);
        goReadMe.putExtra("title",pageTitle);
        startActivity(goReadMe);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btGetSmsCode://获取验证码
                getSmsCode();
                break;
            case R.id.tvUserAgree:
                String agreeSetting = this.getResources().getString(R.string.user_agree_settings);
                gotoWebviewBrowser(MyConstant.WEB_PRIVACY,agreeSetting);
            case R.id.tvPrivacy:
                String userPrivacy = this.getResources().getString(R.string.user_privacy_settings);
                gotoWebviewBrowser(MyConstant.WEB_PRIVACY,userPrivacy);
                break;
            case R.id.btSureRegist:  //注册按钮
                 mMobileNum = mDataBinding.edtMobileNum.getText().toString().trim();      //手机号
                 mPwd = mDataBinding.edtPwd.getText().toString().trim();                //密码
                 mPwdSure = mDataBinding.edtPwdSure.getText().toString().trim();        //确认密码
                 mSmsCode = mDataBinding.edtSmsCode.getText().toString().trim();
                 //验证输入是否正确
                boolean isCorrect = checkInput();

                if(isCorrect) {
                    mViewModel.regist(mMobileNum,mPwd,mSmsCode);
                }
        }
    }

    /**
     * 检查用户输入的字段是否合法
     * @return boolean : true合法，false不合法
     */
    public boolean checkInput() {
        boolean isCorrect = true;
        WeakReference<Context> weakReferenceContext = new WeakReference<>(RegistActivity.this);

        //手机号要恢复
        /*if(isCorrect) {
            isCorrect = CommonUtil.checkMobile(mMobileNum,weakReferenceContext,true);
        }*/

        //密码
        if(isCorrect) {
            isCorrect = CommonUtil.checkPassword(mPwd,weakReferenceContext,0);    //检查密码
        }
        //确认密码
        if(isCorrect) {
            isCorrect = CommonUtil.checkPassword(mPwdSure,weakReferenceContext,3); //检查确认密码
        }

        if(isCorrect) {
            //对比两此密码是否一致
            if (!mPwd.equals(mPwdSure)) {
                Toast.makeText(this,R.string.password_sure_incorrect,Toast.LENGTH_SHORT).show();
                mDataBinding.edtPwdSure.setText("");
                mDataBinding.edtPwdSure.setFocusable(true);
                isCorrect = false;
            }
        }

        //短信码
        if(isCorrect) {
            if (TextUtils.isEmpty(mSmsCode)) {
                Toast.makeText(this,R.string.smscode_empty,Toast.LENGTH_SHORT).show();
                isCorrect = false;
            }
        }

        if(isCorrect) {
            if(!mDataBinding.checkAgree.isChecked()) {
                Toast.makeText(this,R.string.please_agree,Toast.LENGTH_SHORT).show();
                isCorrect = false;
            }
        }
        return isCorrect;
    }

    /**
     * 获取短信验证码
     */
    private void getSmsCode() {
        String mobile = mDataBinding.edtMobileNum.getText().toString();
        WeakReference<Context> weakReferenceContext = new WeakReference<>(RegistActivity.this);

        //手机号格式检查
       boolean isCorrect = CommonUtil.checkMobile(mobile,weakReferenceContext,true);
       if(isCorrect) {
           mViewModel.getSmsCode(mobile,"USER_REGISTER");
       }
    }
}